import {
  Controller,
  Get,
  Put,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  ParseIntPipe,
  ClassSerializerInterceptor,
  UseInterceptors,
} from '@nestjs/common';
import { UserService } from './user.service';
import { UpdateUserDto } from './dto/update-user.dto';
import { ChangePasswordDto } from './dto/change-password.dto';
import { PaginationDto } from '../../common/dto/pagination.dto';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { RolesGuard } from '../../common/guards/roles.guard';
import { Roles } from '../../common/decorators/roles.decorator';
import { CurrentUser } from '../../common/decorators/current-user.decorator';

/**
 * 用户控制器
 */
@Controller('users')
@UseGuards(JwtAuthGuard)
@UseInterceptors(ClassSerializerInterceptor)
export class UserController {
  constructor(private readonly userService: UserService) {}

  /**
   * 获取当前用户信息
   */
  @Get('profile')
  async getProfile(@CurrentUser('id') userId: number) {
    return this.userService.findById(userId);
  }

  /**
   * 更新当前用户信息
   */
  @Put('profile')
  async updateProfile(
    @CurrentUser('id') userId: number,
    @Body() updateUserDto: UpdateUserDto,
  ) {
    return this.userService.update(userId, updateUserDto);
  }

  /**
   * 修改密码
   */
  @Put('password')
  async changePassword(
    @CurrentUser('id') userId: number,
    @Body() changePasswordDto: ChangePasswordDto,
  ) {
    await this.userService.changePassword(userId, changePasswordDto);
    return { message: '密码修改成功' };
  }

  /**
   * 获取用户列表（仅管理员）
   */
  @Get()
  @Roles('admin')
  @UseGuards(RolesGuard)
  async findAll(@Query() paginationDto: PaginationDto) {
    return this.userService.findAll(
      paginationDto.page,
      paginationDto.limit,
    );
  }

  /**
   * 获取指定用户信息（仅管理员）
   */
  @Get(':id')
  @Roles('admin')
  @UseGuards(RolesGuard)
  async findOne(@Param('id', ParseIntPipe) id: number) {
    return this.userService.findById(id);
  }

  /**
   * 更新用户信息（仅管理员）
   */
  @Put(':id')
  @Roles('admin')
  @UseGuards(RolesGuard)
  async update(
    @Param('id', ParseIntPipe) id: number,
    @Body() updateUserDto: UpdateUserDto,
  ) {
    return this.userService.update(id, updateUserDto);
  }

  /**
   * 切换用户状态（仅管理员）
   */
  @Put(':id/toggle-status')
  @Roles('admin')
  @UseGuards(RolesGuard)
  async toggleStatus(@Param('id', ParseIntPipe) id: number) {
    return this.userService.toggleStatus(id);
  }

  /**
   * 删除用户（仅管理员）
   */
  @Delete(':id')
  @Roles('admin')
  @UseGuards(RolesGuard)
  async remove(@Param('id', ParseIntPipe) id: number) {
    await this.userService.remove(id);
    return { message: '用户删除成功' };
  }
}

